package com.seestech.sell.web.cloudDisk;

import com.alibaba.fastjson.JSONArray;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.config.ApplicationConfig;
import com.seestech.sell.common.utils.*;
import com.seestech.sell.domain.model.Directory;
import com.seestech.sell.domain.model.FileInfo;
import com.seestech.sell.domain.model.User;
import com.seestech.sell.domain.model.enums.DirectoryTypeEnums;
import com.seestech.sell.domain.model.enums.FileTypeEnums;
import com.seestech.sell.domain.model.enums.StatusEnums;
import com.seestech.sell.service.IDirectoryService;
import com.seestech.sell.service.IFileService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by idiot on 2016/12/20.
 * @description 管理目录
 */
@Controller
@RequestMapping(value = "cloudDisk/content")
public class ContentController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(ContentController.class);

    @Resource
    private IDirectoryService directoryService;
    @Resource
    private IFileService fileService;
    @Resource
    private ApplicationConfig applicationConfig;

    //加载page页面
    @RecordLog(value = "加载公共素材库页面")
    @RequiresPermissions(value = "cloudDisk:content:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(Model model){
        User user = getUser();
        if(user == null){
            logger.error("加载公共素材库页面======>>>>>>>>用户信息失效，请重新登录");
            return "login";
        }
        return "cloudDisk/content/page";
    }

    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Model model, FileInfo info, Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize){
        User user = getUser();
        if(user == null){
            logger.error("加载素材库文件信息======>>>>>>>>用户信息失效，请重新登录");
            return "login";
        }
        //获取这个用户所在企业相关的用户信息
        Set<Long> userIds = getUserIds(user);
        userIds.add(user.getUserId());
        info.setUserIds(userIds);
        info.setCreateUser(null);
        info.setStatus(StatusEnums.VALID.getValue());
        //该目录下的文件信息
        List<FileInfo> fileList = fileService.getFilesByFileInfo(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", fileList);
        return "cloudDisk/content/data";
    }

    @RequestMapping(value = "materialData", method = RequestMethod.POST)
    public String materialData(Model model, FileInfo info, Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize){
        //该目录下的文件信息
        List<FileInfo> fileList = fileService.getFilesByFileInfo(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", fileList);
        return "cloudDisk/content/materialData";
    }

    //前往编辑页面
    /*@Deprecated
    @RequestMapping(value = "directory/toUpdate", method = RequestMethod.GET)
    public String toAdd(Model model, Directory info){
        //如果父级编号不存在 加载所有的父级目录
        if(info.getParentDirectoryId() == null){
            if(info.getType() == 2){    //当Type为2 时 表示是加载个人素材库
                info.setCreateUser(getUser().getUserId());      //设置当前用户
            }
            List<Directory> parentDiretories = directoryService.getDirectoriesByDirectory(info);
            model.addAttribute("parentDiretories", parentDiretories);
        }else {
            Directory directory = directoryService.getDirectoryByDirectoryId(info.getParentDirectoryId());
            model.addAttribute("parentDirectory", directory);
        }
        model.addAttribute("type", info.getType());
        return "cloudDisk/content/update";
    }*/

    //编辑目录信息
    /*@Deprecated
    @RecordLog(value = "修改目录信息")
    @RequestMapping(value = "directory/update", method = RequestMethod.POST)
    public void update(Model model, Directory info){
        //directoryId为空时表示   新增操作
        if(info.getDirectoryId() == null){
            info.setCreateUser(getUser().getUserId());      //设置创建用户
            info.setPathCode(EncodeMD5.GetMD5Code(String.valueOf(IdGen.get().nextId())));   //为避免目录覆盖 由系统生成
            directoryService.insert(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "新增目录信息成功");
        }else {     //修改操作
            directoryService.update(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "修改目录信息成功");
        }
    }*/

    //前往上传文件页面
    @RequestMapping(value = "file/toUpload", method = RequestMethod.GET)
    public String toUpload(Model model, Directory info){
        //获取所有素材目录
        List<Directory> list = directoryService.getDirectoriesByDirectory(info);
        model.addAttribute("directories", JSONArray.toJSONString(list));
        return "cloudDisk/content/upload";
    }

    //加载公共素材库
    @RequestMapping(value = "material", method = RequestMethod.GET)
    public String material(Model model){
        //获取公共素材库所属的目录信息
        List<Directory> list = directoryService.getDirectoriesByType(DirectoryTypeEnums.One.getValue());
        model.addAttribute("directories", JSONArray.toJSONString(list));
        return "cloudDisk/content/material";
    }

    /**
     * 上传文件操作
     * @param path 前台的当前时间毫秒   当做目录
     * @param id   文件的id  之后用于临时目录
     * fileType 文件的类型   1文本 2图片 3视频 4其他
     * @return
     */
    @RecordLog(value = "上传文件信息")
    @RequestMapping(value = "file/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(String path, String id, Long directoryId){
        User user = getUser();
        if(user == null){
            logger.error("上传文件失败======>用户信息失效，请重新登录");
            return ResponseUtils.responseError("用户信息失效，请重新登录");
        }
        if (directoryId == null){
            logger.error("目录编号不能为空");
            return ResponseUtils.responseError("无效的目录");
        }
        String uploadPath; //上传路径
        int fileType = -1;
        //根据目录id获取目录路径
        uploadPath = directoryService.getDirectoryPathBydirectoryId(directoryId);
        uploadPath = FileUtils.getWindowsPath(FileUtils.addPathSeparate(applicationConfig.getBaseDirectory(), uploadPath, path));
        logger.info("上传路径："+ uploadPath +"=====存储目录："+ path);
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request_local.get();
        // 如果大于1说明是分片处理
        int chunks = 1;
        int chunk = 0;
        //取得request中的所有文件名
        Iterator<String> iterator = multiRequest.getFileNames();
        if(multiRequest.getParameter("chunks") != null){
            chunks = Integer.parseInt(multiRequest.getParameter("chunks"));
            chunk = Integer.parseInt(multiRequest.getParameter("chunk"));
        }

        try {
            while(iterator.hasNext()) {
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iterator.next());
                if (file != null) {
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();

                    //获取文件拓展名
                    String extName = FileUtils.getExtName(myFileName);
                    //根据拓展名获取文件类型
                    fileType = FileUtils.getFileTypeByExtName(extName);
                    if(fileType == -1){
                        logger.error("上传文件失败======>【原因】：文件拓展名检测不符合");
                        return ResponseUtils.responseError("上传失败，文件后缀不符合");
                    }
                    //新文件名
                    String newFileName;
                    // 临时目录用来存放所有分片文件
                    File tempFileDir = new File(FileUtils.buildFileByPath(uploadPath), id);

                    boolean uploadDone = isUploadFileDone(file, tempFileDir, myFileName, chunk, chunks);

                    // 所有分片文件都上传完成
                    // 将所有分片文件合并到一个文件中  得到 destTempFile 就是最终的文件  然后保存即可
                    if (uploadDone) {
                        File destTempFile = new File(uploadPath, myFileName);
                        for (int i = 0; i < chunks; i++) {
                            File partFile = new File(tempFileDir, myFileName + "_" + i + ".part");
                            //合并分片文件
                            FileUtils.copyFile(partFile, destTempFile);
                        }
                        //重命名文件
                        newFileName = System.currentTimeMillis()+StringUtils.randomValue(10000)+"."+extName;
                        File finalFile = new File(uploadPath, newFileName);
                        if(destTempFile.renameTo(finalFile)){
                            logger.info("================>>>重命名文件成功........."+finalFile.getName());
                        }

                        //删除临时文件夹 以及里面的文件
                        FileUtils.deleteDirectory(tempFileDir);

                        String result = FileUtils.removeBaseDir(applicationConfig.getUploadUrl(), finalFile.getPath());
                        result = FileUtils.getTrulyPath(result);
                        logger.info("===========" + result+"=======");

                        //更新数据库
                        FileInfo fileInfo = new FileInfo();
                        fileInfo.setFileName(finalFile.getName());  //更改之后的文件名称（重命名）
                        fileInfo.setOldName(myFileName);            //源文件名称
                        fileInfo.setDirectoryId(directoryId);
                        fileInfo.setFileType(fileType);
                        fileInfo.setDirectoryPath(path);
                        fileInfo.setFilePath(result);       //设置文件上传之后的地址
                        fileInfo.setCreateUser(user.getUserId());   //设置用户编号
                        //如果是图片   获取图片的尺寸
                        if(fileType == FileTypeEnums.jpeg.getValue()){
                            int[] size = ImageUtils.getImageSize(finalFile.getPath());
                            fileInfo.setWidth(size[0]);
                            fileInfo.setHeight(size[1]);
                        }
                        fileService.upload(fileInfo);
                    } else {
                        // 临时文件创建失败  删除临时文件夹 以及里面的文件
                        if (chunk == chunks -1) {
                            FileUtils.deleteDirectory(tempFileDir);
                            return ResponseUtils.responseError("上传文件失败");
                        }
                    }
                }
            }
        }catch (Exception e){
            logger.error("上传文件失败======>【原因】："+e.getMessage());
            return ResponseUtils.responseError("上传文件失败");
        }
        return ResponseUtils.responseSuccess("上传文件成功");
    }
}
